package com.bawei.module_detail.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import com.bawei.lib_common.mvi.base.BaseMVIFragment
import com.bawei.lib_common.utils.HistoryDebugUtils
import com.bawei.lib_common.utils.UserUtils
import com.bawei.lib_storage.room.FavoriteManager
import com.bawei.module_detail.R
import com.bawei.module_detail.adapter.RecommendAdapter
import com.bawei.module_detail.databinding.FragmentRecommendBinding
import com.bawei.module_detail.intent.CommentIntent
import com.bawei.module_detail.model.entity.RecommendSimpleVideoEntity
import com.bawei.module_detail.state.CommentState
import com.bawei.module_detail.viewmodel.CommentViewModel
import com.bumptech.glide.Glide
import com.google.gson.Gson
import kotlinx.coroutines.launch


class RecommendFragment(
    private val pauseVideo: () -> Unit,
    private val playVideo: () -> Unit,
    private val video_item : String
) : BaseMVIFragment() {
    private lateinit var viewModel: CommentViewModel
    private lateinit var binding : FragmentRecommendBinding
    private lateinit var list : List<RecommendSimpleVideoEntity>
    private lateinit var adapter : RecommendAdapter
    private lateinit var videoUser : RecommendSimpleVideoEntity
    private var like = false
    override fun generateViewModel() {
        viewModel = ViewModelProvider(requireActivity()).get(CommentViewModel::class.java)
    }

    override fun lazyLoad() {

    }

    override fun getFragmentRootView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentRecommendBinding.inflate(layoutInflater, container, false)
        return binding.root
    }


    override fun initView() {
        super.initView()
        videoUser = Gson().fromJson(video_item, RecommendSimpleVideoEntity::class.java)
        adapter = RecommendAdapter()
        binding.rvVideos.layoutManager = LinearLayoutManager(requireContext())
        binding.rvVideos.adapter = adapter
        binding.tvUsername.setText(videoUser.name)
        binding.tvBio.setText(videoUser.title)
        binding.tvStats.setText(videoUser.ctime)
        Glide.with(requireContext()).load(videoUser.avatar_url).circleCrop().into(binding.ivAvatar)
        HistoryDebugUtils.testQueryHistory()
        getFavorite()
    }

    override fun initData() {
        super.initData()
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                viewModel.intents.send(CommentIntent.getRecommendSimpleVideo(0,30))
            }
        }
        binding.layoutShare.setOnClickListener {
            getShare()
            pauseVideo()
        }

        binding.layoutLike.setOnClickListener {
            if (like){
                binding.islike.setImageResource(R.drawable.baseline_favorite_24)
                like = false
            }else{
                binding.islike.setImageResource(R.drawable.baseline_favorite_border_24)
                like = true
            }

        }
        // 收藏按钮点击
        binding.layoutFavorite.setOnClickListener {
            lifecycleScope.launch {
                repeatOnLifecycle(Lifecycle.State.STARTED) {
                    val isFavorite = FavoriteManager.isFavorite(videoUser.userid, videoUser.id.toString())
                    if (isFavorite) {
                        FavoriteManager.removeFavorite(videoUser.userid, videoUser.id.toString())
                        Toast.makeText(requireContext(), "取消收藏", Toast.LENGTH_SHORT).show()
                    } else {
                        val userId = UserUtils.getCurrentUserId().ifEmpty { UserUtils.getDefaultUserId() }
                        FavoriteManager.addFavorite(
                            userId,
                            videoUser.userid,
                            videoUser.title,
                            videoUser.videomainimag,
                            videoUser.description,
                            videoUser.avatar_url,
                            videoUser.name,
                            videoUser.videopath,
                            videoUser.channelid
                        )
                        Toast.makeText(requireContext(), "收藏成功", Toast.LENGTH_SHORT).show()
                    }
                    // 操作后立即刷新图标
                    updateFavoriteIcon()
                }
            }
        }
    }

    fun getFavorite(){
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                val isFavorite = FavoriteManager.isFavorite(videoUser.userid,videoUser.id.toString())
                if (isFavorite){
                    binding.isfavorite.setImageResource(R.drawable.baseline_star_border_24)
                }else{
                    binding.isfavorite.setImageResource(R.drawable.ic_star)
                }
            }
        }
    }
    // 刷新图标方法
    private fun updateFavoriteIcon() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                val isFavorite = FavoriteManager.isFavorite(videoUser.userid, videoUser.id.toString())
                if (isFavorite) {
                    binding.isfavorite.setImageResource(R.drawable.ic_star)
                } else {
                    binding.isfavorite.setImageResource(R.drawable.baseline_star_border_24)
                }
            }
        }
    }

    override fun handleState() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                viewModel.commentStateFlow.collect{
                    when(it){
                        CommentState.Empty -> {}
                        CommentState.init -> {}
                        is CommentState.onFailed -> {}
                        is CommentState.onSuccess -> {
                            if (it.type == "hot"){
                                list = it.list as List<RecommendSimpleVideoEntity>
                                list.forEachIndexed { index, item ->
                                    android.util.Log.d("RecommendFragment", "index=$index, name=${item.name}, desc=${item.description}")
                                }
                                adapter.setList(list)
                                adapter.notifyDataSetChanged()
                            }
                        }
                    }
                }
            }
        }
    }
}